package com.wyg.learn.netty;

import com.wyg.learn.customer.ClientBoot;
import com.wyg.learn.impl.HelloServiceImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;

/**
 * @description:
 * @author: WYG
 * @time: 2020/10/10 9:35
 */

public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //获取客户端发送的消息，并调用服务
        System.out.println("msg = " + msg);
        //客户端在调用服务器服务的时候需要定义协议
        //比如每次发消息时必须以某个字符串开头“HelloService#hello#....”
        String[] all = msg.toString().split("#");
        // System.out.println(all[0]+":"+all[1]+":"+all[2]);
        // String ClassName = all[0];
        String method = all[1];
        String params = all[2];
        int first = Integer.parseInt(params.split(",")[0]);
        int second = Integer.parseInt(params.split(",")[1]);
        // System.out.println(first + ":" + second);
        Class aClass = Class.forName("com.wyg.learn.impl."+"ArithmeticImpl");
        System.out.println(aClass);
        Method classMethod = aClass.getMethod(method,int.class,int.class);
        System.out.println(classMethod);
        int result = (int) classMethod.invoke(aClass.newInstance(), first, second);
        //System.out.println(classMethod.invoke(aClass, 1, 2));
        ctx.writeAndFlush(result);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
